// 定义chooseIndex与各个子组件之间的映射关系
const IndexMap = {
    1: 'a',
    2: 'b',
    3: 'c'
}
export default {
    inject: ['main'],
    props: {
        id: { // 组件的标识，用于表单验证失败后精确获取报错组件
            required: true,
            type: Number
        }
    },
    methods: {
        handlePre() {
            this.main.chooseIndex > 1 && this.main.chooseIndex--
        },
        handleNext() {
            this.validateFormData().then(() => {
                this.main.chooseIndex < 3 && this.main.chooseIndex++
            })
        },
        validateFormData() {
            return new Promise((resolve, reject) => {
                console.log(`${IndexMap[this.id]}组件进行了表单验证`)
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        const key = IndexMap[this.id]
                        this.main.formData[key] = this.formData
                        resolve(this.formData)
                    } else {
                        this.$message.warning('表单验证失败')
                        reject(this.id)
                    }
                });
            })
        },
        handleSubmit() {
            this.validateFormData().then((res) => {
                // 执行主组件的提交方法
                this.main.handleSub()
                this.main.chooseIndex = 1
                this.main.showItems = false
            })

        },
        handleCancel() {
            this.main.formData = {}
            this.main.showItems = false
        }
    },
    beforeMount() {
        if (this.main.type === 'edit') {
            const asyncData = JSON.parse(JSON.stringify(this.main.asyncData))
            for (let key in this.formData) {
                this.formData[key] = asyncData[key]
            }
        }
    }
}
